using BitTorrent.Bencode;
using BitTorrent.Bencode.Collections;
using BitTorrent.File.Exceptions;

namespace BitTorrent.File {
    internal class SingelFile : Info {
        public SingelFile() {
        }

        public SingelFile(Dictionary info) : base(info) {
            Name = GetName(info);
            Length = GetLength(info);
        }

        /// <summary>
        /// Name of the file.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// The length of the file in bytes (if in single file mode else 0).
        /// </summary>
        public long Length { get; set; }

        internal override Dictionary GetDictionary() {
            var dictionary = base.GetDictionary();

            dictionary.Add((ByteString)"name", new ByteString { String = Name });
            dictionary.Add((ByteString)"length", new Integer { Value = Length });

            return dictionary;
        }

        private static string GetName(Dictionary info) {
            if (!info.ContainsKey("name")) {
                throw new TorrentFileException("No info name field found");
            }

            var name = info["name"] as ByteString;
            if (name == null) {
                throw new TorrentFileException("name is not represented by a Bencode.ByteString");
            }

            return name.String;
        }

        private static long GetLength(Dictionary info) {
            if (!info.ContainsKey("length")) {
                return 0;
            }

            var length = info["length"] as Integer;
            if (length == null) {
                return 0;
            }

            return length.Value;
        }

    }
}